package cn.iotnc.camera.util

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.net.wifi.WifiManager
import androidx.annotation.CheckResult
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.conflate
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info

fun Context.isWifiConnected(): Boolean {
    val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
    val wifiInfo = wifiManager.connectionInfo
    return wifiInfo.ssid.isNotEmpty()
}

@CheckResult
@ExperimentalCoroutinesApi
fun Context.watchWifiState(): Flow<Boolean> = callbackFlow<Boolean> {
    val receiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            when (intent?.action) {
                WifiManager.RSSI_CHANGED_ACTION ->
                    AnkoLogger("WifiState").info { "wifi信号强度变化" }
                WifiManager.NETWORK_STATE_CHANGED_ACTION -> {
                    val info =
                        intent.getParcelableExtra<NetworkInfo>(WifiManager.EXTRA_NETWORK_INFO)
                    if (info?.state == NetworkInfo.State.DISCONNECTED) {
                        AnkoLogger("WifiState").info { "wifi断开" }
                        safeOffer(false)
                    } else if (info?.state == NetworkInfo.State.CONNECTED) {
                        val wifiManager =
                            context?.applicationContext?.getSystemService(Context.WIFI_SERVICE) as WifiManager
                        val wifiInfo = wifiManager.connectionInfo
                        //获取当前wifi名称
                        AnkoLogger("WifiState").info { "连接到网络 ${wifiInfo.ssid}" }
                        safeOffer(true)
                    }
                }
                WifiManager.WIFI_STATE_CHANGED_ACTION -> {
                    val wifiState = intent.getIntExtra(
                        WifiManager.EXTRA_WIFI_STATE,
                        WifiManager.WIFI_STATE_DISABLED
                    )
                    if (wifiState == WifiManager.WIFI_STATE_DISABLED) {
                        AnkoLogger("WifiState").info { "系统关闭wifi" }
                    } else if (wifiState == WifiManager.WIFI_STATE_ENABLED) {
                        AnkoLogger("WifiState").info { "系统开启wifi" }
                    }
                }
                else -> {
                }
            }
        }
    }
    val filter = IntentFilter().apply {
        addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION)
        addAction(WifiManager.WIFI_STATE_CHANGED_ACTION)
        addAction(ConnectivityManager.CONNECTIVITY_ACTION)
    }
    registerReceiver(receiver, filter)
    awaitClose {
        unregisterReceiver(receiver)
    }
}.conflate()